﻿using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;
using System.Collections.Generic;
using System.Globalization;

namespace Vitus.Featured.Settings
{
    public class FeaturedSettingsHooks : ContentDefinitionEditorEventsBase
    {
        public FeaturedSettingsHooks()
        {
        }

        public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != "FeaturedPart")
            {
                yield break;
            }

            var settings = definition.Settings.GetModel<FeaturedSettings>();

            yield return DefinitionTemplate(settings);
        }

        public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            if (builder.Name != "FeaturedPart")
                yield break;

            var settings = new FeaturedSettings();

            updateModel.TryUpdateModel(settings, "FeaturedSettings", null, null);

            // update the settings builder
            builder.WithSetting("FeaturedSettings.Mode", settings.Mode.ToString("G"));
            builder.WithSetting("FeaturedSettings.TitlePartUsageMode", settings.TitlePartUsageMode.ToString("G"));
            builder.WithSetting("FeaturedSettings.TitleMaxLength", settings.TitleMaxLength.ToString(CultureInfo.InvariantCulture));
            builder.WithSetting("FeaturedSettings.BodyPartUsageMode", settings.BodyPartUsageMode.ToString("G"));
            builder.WithSetting("FeaturedSettings.BodyMaxLength", settings.BodyMaxLength.ToString(CultureInfo.InvariantCulture));

            yield return DefinitionTemplate(settings);
        }
    }
}
